package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.Constant.SearchConstant;
import com.atguigu.gulimall.search.config.ElasticSearchConfig;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.SearchService;
import com.atguigu.gulimall.search.vo.AttrResponseVo;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {
    @Resource
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult getSearchResult(SearchParam searchParam) {
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        SearchResult searchResult = null;
        try {
            SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            searchResult = buildSearchResult(searchResponse, searchParam);

        } catch (IOException e) {
            log.error("商品检索异常：{}", e.getMessage());
        }
        return searchResult;
    }

    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        //检索总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);

        //查询的每页显示的记录数
        searchResult.setPageNum(searchParam.getPageNum());

        //总页数
        searchResult.setTotalPages((int) (total % SearchConstant.PRODUCT_PAGESIZE == 0 ? total / SearchConstant.PRODUCT_PAGESIZE : total / SearchConstant.PRODUCT_PAGESIZE + 1));

        //页码
        List<Integer> pageNavs = new ArrayList<>();
        for (Integer i = 1; i <= searchResult.getTotalPages(); i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        //没页显示的内容数据
        List<SkuEsModel> list = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit documentFields : hits.getHits()) {
                String sourceAsString = documentFields.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                HighlightField skuTitle = documentFields.getHighlightFields().get("skuTitle");
                if (skuTitle != null && skuTitle.getFragments().length > 0) {
                    skuEsModel.setSkuTitle(skuTitle.getFragments()[0].toString());
                }
                list.add(skuEsModel);
            }
        }
        searchResult.setProducts(list);

        //品牌聚合
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        Terms brandAgg = searchResponse.getAggregations().get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

            String brandId = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brandId));

            Terms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            Terms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        //分类聚合
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        Terms catalogAgg = searchResponse.getAggregations().get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catalogId = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));

            Terms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        //5 查询涉及到的所有属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        //ParsedNested用于接收内置属性的聚合
        ParsedNested parsedNested=searchResponse.getAggregations().get("attrs");
        ParsedLongTerms attrIdAgg=parsedNested.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            //5.1 查询属性id
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            Long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            Aggregations subAttrAgg = bucket.getAggregations();
            //5.2 查询属性名
            ParsedStringTerms attrNameAgg=subAttrAgg.get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //5.3 查询属性值
            ParsedStringTerms attrValueAgg = subAttrAgg.get("attrValueAgg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                String attrValue = attrValueAggBucket.getKeyAsString();
                attrValues.add(attrValue);
            }
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);

        // 6. 构建面包屑导航
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            List<SearchResult.NavVo> navVos = attrs.stream().map(attr -> {
                String[] split = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //6.1 设置属性值
                navVo.setNavValue(split[1]);
                //6.2 查询并设置属性名
                try {
                    R r = productFeignService.info(Long.parseLong(split[0]));
                    if (r.getCode() == 0) {
                        AttrResponseVo attrResponseVo = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrResponseVo>() {
                        });
                        navVo.setName(attrResponseVo.getAttrName());
                    }
                } catch (Exception e) {
                    log.error("远程调用商品服务查询属性失败", e);
                }
                //6.3 设置面包屑跳转链接
                String queryString = searchParam.get_queryString();
                String replace = queryString.replace("&attrs=" + attr, "").replace("attrs=" + attr+"&", "").replace("attrs=" + attr, "");
                navVo.setLink(SearchConstant.QUERY_URL + (replace.isEmpty()?"":"?"+replace));
                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(navVos);
        }

        return searchResult;
    }

    private String getQueryString(SearchParam searchParam, String attr,String key) {
        String queryString = searchParam.get_queryString();
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "UTF-8");
            encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return queryString.replace("&"+key+"=" + encode, "");
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        // 用于构建DSL语句
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //1. 构建bool query
        BoolQueryBuilder booleanQuery = new BoolQueryBuilder();
        //1.1 bool must 根据搜索框keyword检索  "must": [ {"match": {  "skuTitle": "华为" }} ], # 检索出华为
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            booleanQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        //1.2 bool filter 根据分类id检索  { "term": { "catalogId": "225" } },
        if (searchParam.getCatalog3Id() != null) {
            booleanQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //1.3 bool filter  根据品牌id检索  { "terms": {"brandId": [ "2"] } },
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            booleanQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //1.4 bool filter  根据库存检索 { "term": { "hasStock": "false"} },
        if (searchParam.getHasStock() != null) {
            booleanQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //1.5 bool filter  根据价格检索 {"range": {"skuPrice": { "gte": 1000,lte": 7000}}}, skuPrice:1000_7000 ||1000_
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] price = searchParam.getSkuPrice().split("_");
            if (price.length == 2) {
                rangeQueryBuilder.gte(price[0]);
                rangeQueryBuilder.lte(price[1]);
            } else {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(price[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")) {
                    rangeQueryBuilder.gte(price[0]);
                }
            }
            booleanQuery.filter(rangeQueryBuilder);
        }
        //1.6 根据属性检索 "nested": {"path": "attrs", # 聚合名字"query": {"bool": {"must": [{"term": { "attrs.attrId": { "value": "6"} }}]}}}
        //attrs=1_5寸:8寸&attrs=2_16G:8G
        List<String> attrs = searchParam.getAttrs();
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if (attrs!=null&&attrs.size() > 0) {
            attrs.forEach(attr->{
                String[] attrSplit = attr.split("_");
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrSplit[0]));
                String[] attrValues = attrSplit[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
            });
        }
        NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
        booleanQuery.filter(nestedQueryBuilder);
        //1.X bool query构建完成
        searchSourceBuilder.query(booleanQuery);

        //2.0  排序 "sort": [ {"skuPrice": {"order": "desc" } } ],  排序条件：sort=price/salecount/hotscore_desc/asc
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String[] sort = searchParam.getSort().split("_");
            SortOrder order = sort[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(sort[0], order);
        }

        //2.1 分页
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * SearchConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(SearchConstant.PRODUCT_PAGESIZE);

        //2.2 高亮显示  "highlight": {"fields": {"skuTitle": {}}, # 高亮的字段
        // "pre_tags": "<b style='color:red'>",  # 前缀"post_tags": "</b>"},
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("skuTitle").preTags("<b style='color:red'>").postTags("</b>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //3.0 品牌聚合   "brandAgg": {"terms": {"field": "brandId","size": 10},
        AggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId").size(10);

        //3.1 品牌名称聚合(子聚合)"aggs": { # 子聚合 "brandNameAgg": {  # 每个商品id的品牌 "terms": {"field": "brandName","size": 10}},
        AggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName").size(10);
        //3.2 品牌图片聚合(子聚合)"brandImgAgg": {"terms": {"field": "brandImg","size": 10}}
        AggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg").size(10);
        brandAgg.subAggregation(brandNameAgg);
        brandAgg.subAggregation(brandImgAgg);
        searchSourceBuilder.aggregation(brandAgg);

        //4.0  分类聚合     "catalogAgg":{"terms": {"field": "catalogId","size": 10},
        AggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(10);

        //4.1  分类名称聚合(子聚合)"aggs": {"catalogNameAgg": {"terms": {"field": "catalogName","size": 10}}}
        AggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(10);
        catalogAgg.subAggregation(catalogNameAgg);
        searchSourceBuilder.aggregation(catalogAgg);

        //5.0   属性聚合 "attrs":{"nested": {"path": "attrs" },
        NestedAggregationBuilder nestedAggregationBuilder = new NestedAggregationBuilder("attrs", "attrs");
        //按照attrId聚合     //按照attrId聚合之后再按照attrName和attrValue聚合
        TermsAggregationBuilder attrIdAgg    = AggregationBuilders.terms("attrIdAgg"   ).field("attrs.attrId");
        TermsAggregationBuilder attrNameAgg  = AggregationBuilders.terms("attrNameAgg" ).field("attrs.attrName");
        TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue");
        attrIdAgg.subAggregation(attrNameAgg);
        attrIdAgg.subAggregation(attrValueAgg);

        nestedAggregationBuilder.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);

        log.info("构建的DSL语句 {}", searchSourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{SearchConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;

    }
}
